package com.tencent.yolov8ncnn;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;

//import androidx.core.widget.NestedScrollView;
//
//
//import com.blankj.utilcode.util.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ViewSaveImageUtils {
    private static Context mcontext;

    /**
     * 把一个View转为图片保存到本地
     *
     * @param view
     * @param ener
     */
    public static void viewSaveToImage(View view, OnSaveListEner ener) {
        if (ener != null) ener.onStart();
        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);
        FileOutputStream fos;
        if (checkSDCardAvailable()) {
            try {
                // SD卡根目录
                File sdRoot = getDownloadDir();
                File file = new File(sdRoot, System.currentTimeMillis() + ".png");
                fos = new FileOutputStream(file);
                cachebmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                if (ener != null) ener.onSucceed(file.getAbsolutePath());
            } catch (Exception e) {
                if (ener != null) ener.onFailure(e.getMessage());
                e.printStackTrace();
            }
        } else {
            if (ener != null) ener.onFailure("创建文件失败!");
        }
        view.destroyDrawingCache();
        if (ener != null) ener.onFinish();
    }

    /**
     * 把一个View转为图片保存到本地
     *
     * @param view
     * @return
     */
    public static String viewSaveToImage(View view) {
        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        FileOutputStream fos;
        String imagePath = "";
        try {
            if (checkSDCardAvailable()) {
                // SD卡根目录
                File sdRoot = getDownloadDir();
                File file = new File(sdRoot, System.currentTimeMillis() + ".png");

                fos = new FileOutputStream(file);
                imagePath = file.getAbsolutePath();
            } else {
                throw new Exception("创建文件失败!");
            }
            cachebmp.compress(Bitmap.CompressFormat.PNG, 90, fos);

            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


        view.destroyDrawingCache();
        return imagePath;
    }

    /**
     * 把一个View转为Bitmap
     *
     * @param v
     * @return
     */
    public static Bitmap loadBitmapFromView(View v) {
        v.setDrawingCacheEnabled(true);
        v.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        v.setDrawingCacheBackgroundColor(Color.WHITE);

        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

    /**
     * Bitmap保存为图片
     *
     * @param photoBitmap
     * @param path
     * @param photoName
     */
    public static void savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) {
        if (checkSDCardAvailable()) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File photoFile = new File(path, photoName + ".jpg");
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                } else {

                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


//    /**
//     * 把一个View转为Bitmap
//     *
//     * @param scrollView
//     * @return
//     */
//    public static Bitmap getBitmapByView(NestedScrollView scrollView) {
//        int h = 0;
//        Bitmap bitmap = null;
//        for (int i = 0; i < scrollView.getChildCount(); i++) {
//            h += scrollView.getChildAt(i).getHeight();
//        }
//        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
//                Bitmap.Config.RGB_565);
//        final Canvas canvas = new Canvas(bitmap);
//        canvas.drawColor(Color.WHITE); //白色背景
//        scrollView.draw(canvas);
//        return bitmap;
//    }


    public static boolean checkSDCardAvailable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    public interface OnSaveListEner {
        void onStart();

        void onSucceed(String filePath);

        void onFailure(String error);

        void onFinish();
    }


    /**
     * 保存到相册
     *
     * @param bitmap
     */
    public static void saveScreenShot(Context context, Bitmap bitmap) {
        mcontext = context;


        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
        String filename;//声明文件名
        //以保存时间为文件名
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);
        File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件，第一个参数为路径，第二个参数为文件名
        try {
            outStream = new FileOutputStream(file);//创建输入流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();
            /**       这三行可以实现相册更新
             ;//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！*/

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mcontext.sendBroadcast(intent);

//            ToastUtils.showShort( "保存成功");

        } catch (Exception e) {

            Log.e("调用", e.getMessage());
        }
    }


    /**
     * 图片的额存数路径
     *
     * @return
     */
    public static File getDownloadDir() {


        File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (!downloadDir.exists()) {
            downloadDir.mkdir();
        }
        return downloadDir;
    }

}
